package com.cskaoyan.transfer;

import com.cskaoyan.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 创建日期: 2021/11/23 17:33
 *
 * @author ciggar
 * 事务的Demo
 */
public class TransferDemo {

    // 转账的案例
    public static void main(String[] args) throws SQLException {

        Boolean ret = transfer("风华哥","长风",10000);

        if (ret) {
            System.out.println("转账成功...");
        }else {

            System.out.println("转账失败...");
        }

    }


    // 转账的方法
    public static Boolean transfer(String fromName,String toName,Integer money){

        // 获取连接
        Connection connection = JDBCUtils.getConnection();

        // 开启事务
        try {
            connection.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        try {

            // 给fromName扣钱 money
            PreparedStatement preparedStatement = connection.prepareStatement("update account set money = money - ? where name = ?");

            preparedStatement.setInt(1, money);
            preparedStatement.setString(2, fromName);

            // 执行
            int affectedRows = preparedStatement.executeUpdate();

            if (affectedRows != 1) {
                System.out.println("扣钱失败！！！");
                return false;
            }

            int i = 1 / 0;


            // 给toName加钱 money
            PreparedStatement preparedStatement1 = connection.prepareStatement("update account set money = money + ? where name = ?");

            preparedStatement1.setInt(1, money);
            preparedStatement1.setString(2, toName);

            int affectedRows1 = preparedStatement1.executeUpdate();
            if (affectedRows1 != 1) {
                System.out.println("加钱失败");
                return false;
            }else {
                // 提交事务
                connection.commit();
                return true;

            }
        }catch (Exception ex) {
            try {
                connection.rollback();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            System.out.println("回滚成功...");
        }

        return false;

    }



}
